package com.sanglh.tutorial.common.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;

public class AppUtils {
	public static final int FILTER_APPS_ALL = 0;
	public static final int FILTER_APPS_RUNNING = FILTER_APPS_ALL + 1;
	public static final int FILTER_APPS_SYSTEMS = FILTER_APPS_ALL + 2;
	public static final int FILTER_APPS_SDCARD = FILTER_APPS_ALL + 3;
	public static final int FILTER_APPS_NOT_SYSTEMS = FILTER_APPS_ALL + 4;

	// ==========================================================================
	public static ArrayList<ApplicationInfo> getAllKnownApplication(
			Context context) {
		PackageManager pm = context.getPackageManager();
		ArrayList<ApplicationInfo> apps = (ArrayList<ApplicationInfo>) pm
				.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
		if (apps == null) {
			apps = new ArrayList<ApplicationInfo>();
		}
		return apps;
	}

	// ==========================================================================
	public static List<ApplicationInfo> getInstalledApplication(
			Context context, int filterOption) {
		PackageManager pm = context.getPackageManager();
		List<ApplicationInfo> installedAppList = pm
				.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
		if (installedAppList == null) {
			installedAppList = new ArrayList<ApplicationInfo>();
		}
		if (filterOption == FILTER_APPS_SDCARD) {
			List<ApplicationInfo> appList = new ArrayList<ApplicationInfo>();
			for (ApplicationInfo appInfo : installedAppList) {
				if ((appInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
					appList.add(appInfo);
				}
			}
			return appList;
		} else if (filterOption == FILTER_APPS_SYSTEMS) {
			List<ApplicationInfo> appList = new ArrayList<ApplicationInfo>();
			for (ApplicationInfo appInfo : installedAppList) {
				if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
					appList.add(appInfo);
				}
			}
			return appList;
		} else if (filterOption == FILTER_APPS_NOT_SYSTEMS) {
			List<ApplicationInfo> appList = new ArrayList<ApplicationInfo>();
			for (ApplicationInfo appInfo : installedAppList) {
				if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
					appList.add(appInfo);
				}
			}
			return appList;
		} else if (filterOption == FILTER_APPS_RUNNING) {
			List<ApplicationInfo> appList = new ArrayList<ApplicationInfo>();
			List<ActivityManager.RunningAppProcessInfo> procList = getRunningAppProcessesList(context);
			if ((procList == null) || (procList.size() == 0)) {
				return appList;
			}
			// Retrieve running processes from ActivityManager
			for (ActivityManager.RunningAppProcessInfo appProcInfo : procList) {
				if ((appProcInfo != null) && (appProcInfo.pkgList != null)) {
					int size = appProcInfo.pkgList.length;
					for (int i = 0; i < size; i++) {
						ApplicationInfo appInfo = null;
						try {
							appInfo = pm.getApplicationInfo(
									appProcInfo.pkgList[i],
									PackageManager.GET_UNINSTALLED_PACKAGES);
						} catch (NameNotFoundException e) {
							continue;
						}
						if (appInfo != null) {
							appList.add(appInfo);
						}
					}
				}
			}
			return appList;
		} else {
			return installedAppList;
		}
	}

	public static List<ActivityManager.RunningAppProcessInfo> getRunningAppProcessesList(
			Context context) {
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		return am.getRunningAppProcesses();
	}

	public static List<ActivityManager.RecentTaskInfo> getRecentgetRecentTasks(
			Context context) {
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		return am.getRecentTasks(Integer.MAX_VALUE, ActivityManager.RECENT_WITH_EXCLUDED);
	}

//	public static List<ActivityManager.RecentTaskInfo> getRecentAppList(
//			Context context) {
//		ActivityManager am = (ActivityManager) context
//				.getSystemService(Context.ACTIVITY_SERVICE);
//		List<ActivityManager.RecentTaskInfo> taskInfos = am.getRecentTasks(Integer.MAX_VALUE,
//				ActivityManager.RECENT_WITH_EXCLUDED);
//		for (RecentTaskInfo recentTaskInfo : taskInfos) {
//			recentTaskInfo.
//		}
//	}

	// ==========================================================================
	public static String getApplicationLabel(Context context,
			ApplicationInfo info) {
		return info.loadLabel(context.getPackageManager()).toString();

	}

	// ==========================================================================
	public static Drawable getApplicationIcon(Context context,
			ApplicationInfo info) {
		return info.loadIcon(context.getPackageManager());

	}
	
	public static Drawable getApplicationIcon(Context context,
			String pck) {
		PackageManager packageManager = context.getPackageManager();
		try {
			ApplicationInfo info = packageManager.getApplicationInfo(pck, 0);
			return info.loadIcon(packageManager);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return null;

	}

	// ==========================================================================
	// public static long getApplicationSize(Context context, ApplicationInfo
	// info) {
	// PackageManager pm = context.getPackageManager();
	// try {
	// Method getPackageSizeInfo = pm.getClass().getDeclaredMethod(
	// "getPackageSizeInfo", String.class,
	// IPackageStatsObserver.class);
	// getPackageSizeInfo.setAccessible(true);
	// getPackageSizeInfo.invoke(pm, new IPackageStatsObserver.Stub() {
	//
	// @Override
	// public void onGetStatsCompleted(PackageStats pStats,
	// boolean succeeded) throws RemoteException {
	// if (succeeded && pStats != null) {
	// if (pStats != null) {
	// return pStats.cacheSize + pStats.codeSize + pStats.dataSize;
	// }
	// long total = getTotalSize(pStats);
	// data.putLong(ATTR_PKG_STATS, total);
	// CharSequence sizeStr = getSizeStr(total);
	// data.putString(ATTR_PKG_SIZE_STR, sizeStr.toString());
	// } else {
	// Log.w(TAG, "Invalid package stats from PackageManager");
	// }
	//
	// }
	// });
	// } catch (Exception e) {
	// return new File(info.sourceDir).length();
	// }
	//
	// }

	// ==========================================================================
	public static void uninstallApp(Context context, String pkg) {
		Uri packageURI = Uri.parse("package:" + pkg);
		Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE,
				packageURI);
		context.startActivity(uninstallIntent);
	}

	public static void uninstallPkg(Context context, String packageName) {
		// Create new intent to launch Uninstaller activity
		Uri packageURI = Uri.parse("package:" + packageName);
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
		context.startActivity(uninstallIntent);
	}

	public static ArrayList<String> getPermissions(Context context, String pck) {
		PackageManager pm = context.getPackageManager();
		try {
			PackageInfo packageInfo = pm.getPackageInfo(pck,
					PackageManager.GET_PERMISSIONS);
			return new ArrayList<String>(
					Arrays.asList(packageInfo.requestedPermissions));
		} catch (NameNotFoundException e) {
			return null;
		}

	}

	// ==========================================================================
	public static void launchHomeApp(Context context) {
		Intent i = new Intent(Intent.ACTION_MAIN);
		i.addCategory(Intent.CATEGORY_HOME);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(i);
	}

	public static void launchSettingsApp(Context context) {
		Intent i = new Intent(android.provider.Settings.ACTION_SETTINGS);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(i);
	}

	public static void launchCameraApp(Context context) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}
}
